package Offer27_226;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author 23737
 * @time 2021.9.9
 * 二叉树镜像：请完成一个函数，输入一个二叉树，该函数输出它的镜像
 */
public class Test {
    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(4);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(7);
        TreeNode treeNode4 = new TreeNode(1);
        TreeNode treeNode5 = new TreeNode(3);
        TreeNode treeNode6 = new TreeNode(6);
        TreeNode treeNode7 = new TreeNode(9);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode2.right = treeNode5;
        treeNode3.right = treeNode6;
        treeNode3.right = treeNode7;
        TreeNode node = new Solution().mirrorTree(treeNode1);
        System.out.println(node.val);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }
}

/*队列实现，自己根据官方解法实现的*/
class Solution{
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            //先弹出结点的值，并用一个TreeNode保存起来
            TreeNode node = queue.poll();
            //判空，分别添加其左右结点
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
            //最后把左右结点的值进行交换
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        //返回结点的值
        return root;
    }
}

/*栈来实现——————官方题解*/
class SolutionTwo{
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> queue = new Stack<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.pop();
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        return root;
    }
}

/*递归来实现*/
class SolutionThree{
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        //自己画了图终于理解了这个思路
        TreeNode left = root.left;
        /*
        因为先进行的是root.left = mirrorTree(root.right)，root.left的值是递归的root.right
        而最后返回的是一个root结点的值，所以返回的是root.left
        说的有点乱，自己最好画个图辅助理解
        */
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(left);
        return root;
    }
}
